<?php 

/**
 * 手机短信验证码类
 */
class PhoneCaptcha{
    static public function sendSms($phone){
        $CI = &get_instance();
        $code = '1234';
        $CI->load->library('aliyunAPI/SmsSender',NULL,'SMS');
        $res = $CI->SMS->send_captcha($phone,$code);
        if( $res){
            return $res;
        }else{
            throw new Exception('运营商不让给你发那么多信息,待会再试吧!');
        }
    }


	/**
	 * 发送验证码
	 * @param string $phone
	 * @return array	结果数组,其中:
	 * 		error : 错误代码(0为成功)
	 * 		msg	  : 错误消息
	 * 		code  : 成功时发送的验证码
	 */
	static public function send($phone){
		$now = time();
		
		if( !isset($_SESSION) ){
			session_start();
		}
		
		// 防恶意点击:
		// 如果上一次没有验证成功,且间距小于60秒,不给再次发送
		// 如果验证成功,则unset($_SESSION['captcha'])
		if( !empty($_SESSION['captcha']) && !empty($_SESSION['captcha']['time']) ){
			if( $now-$_SESSION['captcha']['time'] < 5 ){
				throw new Exception('一分钟只能发送一条验证码哦,待会再请求吧!');
			}
		}
		// 获取一个小时内发送的短信记录
		$CI = &get_instance();
		$CI->load->database();
		$logs = $CI->db->select('sendTime')
						->where('phone',$phone)
						->where('sendTime >=',$now-3600)
						->get('hs_sms_log')
						->result_array();
		$logsCount = count($logs);
		if( $logsCount > 0 ){
			if( $now - $logs[$logsCount-1]['sendTime'] <60 ){
				throw new Exception('一分钟只能发送一条验证码哦,待会再请求吧!');
			}
			if( $logsCount >=7 ){
				throw new Exception('运营商不给发那么多条验证码!等到'.date('H:i',$logs[0]['sendTime']+3600).'后再试吧!');
			}
		}
		

		$code = mt_rand(1000,9999);
		$_SESSION['captcha'] = array(
			'phone'=>$phone,
			'code'=>$code,
			'time'=>time(),
		);
        
        $CI->load->library('aliyunAPI/SmsSender',NULL,'SMS');
        if( $CI->SMS->captcha($phone,$code) ){
        	// 入库
        	$log = array(
        			'phone'=>$phone,
        			'sendTime'=>time(),
        			'ip'=>sprintf("%u",ip2long($CI->input->ip_address())),
        	);
        	$CI->db->insert('hs_sms_log',$log);
        	
        	return TRUE;
        }else{
        	throw new Exception('运营商不让给你发那么多信息,待会再试吧!');
        }
	}
	/**
	 * 验证短信验证码
	 * @param string $phone	手机号码
	 * @param string $code 	短信验证码
	 * @return boolean
	 */
	static public function check($phone,$code){
	    if ( defined('IS_TEST') && IS_TEST ) {
	        return TRUE;
	    }
	    if( self::isTester($phone, $code) ){
	    	return TRUE;
	    }
	    
		if( !isset($_SESSION) ){
			session_start();
		}
		
		if( empty($_SESSION['captcha']) ){
			return FALSE;
		}
		
		$captcha = $_SESSION['captcha'];

		if( $phone == $captcha['phone'] && $code == $captcha['code'] ){
			unset($_SESSION['captcha']);
			return TRUE;
		}
		return FALSE;
	}
	
	
	static function isTester($phone,$code){
		return $code = '4738' && in_array($phone, array('13602417572','18826121780','13088854884','13580533006'));
	}
}
